const Koa = require('koa');

const app = new Koa();


// 连接数据库
require('./db');
// 错误处理程序
require('koa-onerror')(app);

// 中间件
app.use(require('koa-bodyparser')({
    enableTypes: ['json', 'form', 'text']
}));
app.use(require('koa-logger')());
app.use(require('koa-static')(`${__dirname}/static`));
app.use(async (ctx, next) => {
    ctx.set({
        'Access-Control-Allow-Origin': ctx.headers.origin || '*',
        'Access-Control-Allow-Methods': 'POST, DELETE, PUT, GET'
    });
    await next();
});
// 记录器
//app.use(async (ctx, next) => {
//    const start = new Date();
//    await next();
//    const ms = new Date() - start;
//    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
//});

// 路由
require('mount-koa-routes')(app, `${__dirname}/app/routes`, true);

// 错误处理
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx);
});

module.exports = app;